package com.my.main.shiro.realm;

import com.my.main.base.entity.response.ProfileResult;
import com.my.main.entity.enterprise.EnterpriseUserRelation;
import com.my.main.entity.userAndRight.SysRightsRoleUserRelation;
import com.my.main.entity.userAndRight.SysUser;
import com.my.main.service.enterprise.EnterpriseUserRelationService;
import com.my.main.service.userAndRight.SysRightsRoleService;
import com.my.main.service.userAndRight.SysRightsRoleUserRelationService;
import com.my.main.service.userAndRight.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRightsRoleService sysRightsRoleService;
    @Autowired
    private SysRightsRoleUserRelationService sysRightsRoleUserRelationService;
    @Autowired
    private EnterpriseUserRelationService enterpriseUserRelationService;
    @Autowired
    private Environment env;

    // 认证方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        SysUser user = null;
        // 1.获取用户安全数据
        String phone = (String)authenticationToken.getPrincipal();
        String status = "normal";

        // 2.根据手机号或者用户名（登录名）查询用户
        user = sysUserService.findByUserName(phone);
        if (StringUtils.isEmpty(user)) {
            user = sysUserService.findByMobile(phone);
        }

        //3.判断用户是否存在，用户密码是否和输入密码一致
        if(user != null) {
            // 4.构造安全数据并返回（安全数据：用户基本数据，权限信息 profileResult）
//            String sha384Hex = new Sha384Hash(user.getPassWord()).toBase64();
            ProfileResult result = null;
            // 5.查询该用户是否具有超级管理员身份
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("userId", user.getUserId());
            queryMap.put("limit", 0);
            List<SysRightsRoleUserRelation> list = sysRightsRoleUserRelationService.queryListByMap(queryMap);
            Boolean isAdmin = list.stream().filter(item -> sysRightsRoleService.queryStringId(item.getRoleId()).getIsAdmin()).count() > 0;
            // 6.业务数据缓存
            // 视频管理员登录后将其名下的企业id缓存
            List<String> enterpriseList = new ArrayList<>();
            if (!isAdmin) {
                enterpriseUserRelationService.queryList(queryMap).stream().forEach(item -> enterpriseList.add(item.getEnterpriseId()));
            }
            result = new ProfileResult(user, env.getProperty("app_key"), isAdmin, enterpriseList);
            //5.构造方法：安全数据，密码，realm域名
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result,user.getPassWord(), getName());
            return info;
        }
        //返回null，会抛出异常，标识用户名和密码不匹配
        return null;
    }

    // 授权方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("本地的授權方法");
        return null;
    }

}
